package org.young.admin.service.sys.impl;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.young.admin.common.properties.JWTProperties;
import org.young.admin.common.rpc.RpcCommonService;
import org.young.admin.service.sys.IUserService;
import org.young.common.constant.CommonConstant;
import org.young.common.exception.BizException;
import org.young.common.utils.JwtUtil;
import org.young.common.utils.PasswordUtil;
import org.young.common.utils.RedisUtil;
import org.young.rbac.dao.model.SysUser;

import java.util.HashMap;
import java.util.Map;

/**
 * @author lmhd-emp
 * @date 2021/5/11 15:49
 * @description:
 */
@Slf4j
@Service
public class UserServiceImpl implements IUserService {

	@Autowired
	RpcCommonService rpcCommonService;
	@Autowired
	JWTProperties    jwtProperties;
	@Autowired
	RedisUtil        redisUtil;

	@Override public SysUser checkUserIsEffective(String username, String password) {
		SysUser sysUser = rpcCommonService.sysUserWorkService.getUserByUsername(username);
		if (sysUser == null) {
			throw new BizException(CommonConstant.BASE_ERROR_CODE, "账号不存在！");
		}
		Boolean status = sysUser.getStatus();
		if (CommonConstant.USER_FREEZE.equals(status)) {
			throw new BizException(CommonConstant.BASE_ERROR_CODE, "账号被冻结！");
		}
		Boolean delFlag = sysUser.getDelFlag();
		if (CommonConstant.USER_DELETED.equals(delFlag)) {
			throw new BizException(CommonConstant.BASE_ERROR_CODE, "账号被注销！");
		}
		String pwd = sysUser.getPassword();
		String salt = sysUser.getSalt();
		String encryptPwd = PasswordUtil.encrypt(username, password, salt);
		if (!StringUtils.equals(pwd, encryptPwd)) {
			throw new BizException(CommonConstant.BASE_ERROR_CODE, "密码错误！");
		}
		return sysUser;
	}

	@Override public Map setUserInfoToCache(SysUser user) {
		Map<String,Object> map = new HashMap<>();
		String username = user.getUsername();
		String password = user.getPassword();
		Long expireTime = jwtProperties.getExpireTime();
		Long refreshExpireTime = jwtProperties.getRefreshExpireTime();
		String sign = JwtUtil.sign(username, password, expireTime);
		redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + sign, sign, refreshExpireTime);
		user.setPassword(null);
		user.setSalt(null);
		map.put("token", sign);
		map.put("userInfo", user);
		return map;
	}
}
